import React from 'react'
import {
  ClockHead,
  ClockToday,
  Tag,
  ClockTitle,
  ClockList,
  ClockItem,
  PopUp
} from './style'
import { connect } from 'react-redux'
import { Toast, Modal } from 'antd-mobile'
import {
  activityInfo,
  uploadVideo,
  create,
  praise,
  memberRecords,
  activityRecords
} from '../../api'

class Index extends React.PureComponent {
  weekZn = ['日', '一', '二', '三', '四', '五', '六']
  constructor(prop, state) {
    super(prop)
    let date = new Date()
    this.data = {
      today: date.getDate(),
      week: date.getDay()
    }
    this.state = {
      isShow: false,
      info: '',
      video: '',
      isToday: false,
      memberList: []
    }
  }
  componentDidMount() {
    this.loadActive()
    this.loadMemberList()
  }
  loadActive() {
    activityInfo({
      id: this.props.match.params.id,
      mid: this.props.userInfo.id
    }).then(res => {
      this.setState({
        info: res.data.data
      })
    })
  }
  // 计算今日是否打卡
  checkClock(data) {
    if (this.state.info && this.state.info.member_records) {
      for (const k of this.state.info.member_records) {
        if (k.created_at.split(' ')[0] === data) {
          return true
        }
      }
    }
  }
  loadMemberList() {
    memberRecords({
      mid: this.props.userInfo.id
    }).then(res => {
      this.setState({
        isToday: false,
        memberList: res.data.data
      })
    })
  }
  loadActiveList() {
    activityRecords({
      id: this.props.match.params.id
    }).then(res => {
      this.setState({
        isToday: true,
        memberList: res.data.data
      })
    })
  }
  getPraise(rid, aid) {
    praise({
      praise_id: this.props.userInfo.id,
      record_id: rid,
      activity_id: aid
    }).then(res => {
      Toast.info(res.data.message, 3)
    })
  }
  formatDay(day, f) {
    let date = new Date().getTime()
    let newDate = new Date(date + day * 24 * 60 * 60 * 1000)
    if (f) {
      return (
        newDate.getFullYear() +
        '-' +
        (newDate.getMonth() + 1 < 10
          ? '0' + (newDate.getMonth() + 1)
          : newDate.getMonth() + 1) +
        '-' +
        (newDate.getDate() < 10 ? '0' + newDate.getDate() : newDate.getDate())
      )
    }
    return newDate.getDate()
  }
  showPop() {
    this.setState({
      isShow: true
    })
  }
  hidePop() {
    this.setState({
      isShow: false
    })
  }
  camcorderPlay() {
    document.getElementById('video').click()
  }
  upload() {
    var fileObj = document.getElementById('video').files[0] // js 获取文件对象
    console.log(fileObj)
    if (typeof fileObj == 'undefined' || fileObj.size <= 0) {
      return
    }
    var url = URL.createObjectURL(fileObj)
    console.log(url)
    this.setState({
      video: url
    })
    this.checkLength()
    return false
  }
  checkLength() {
    var fileObj = document.getElementById('video').files[0]
    if (document.getElementById('videoCont').duration > 60) {
      Modal.alert('提示', '亲，打卡视频时长最多60秒哟', [
        { text: '我知道了', onPress: () => console.log('ok') }
      ])
      return false
    }
    var formFile = new FormData()

    formFile.append('file', fileObj)
    uploadVideo(formFile).then(res => {
      if (res.data.code === 0) {
        create({
          activity_id: this.props.match.params.id,
          member_id: this.props.userInfo.id,
          content: res.data.url
        }).then(res => {
          Toast.info(res.data.message, 3)
          this.loadActive()
          if (this.state.isToday) {
            this.loadActiveList()
          } else {
            this.loadMemberList()
          }
        })
      } else {
        Toast.info(res.data.message, 3)
      }
    })
  }

  goRank(id) {
    this.props.history.push('/rank/' + id)
  }
  goDate() {
    let id = this.props.match.params.id
    this.props.history.push('/clockDate/' + id)
  }
  render() {
    return (
      <div>
        <ClockHead>
          {this.weekZn.map((i, index) => (
            <div
              className={index === this.data.week ? 'atthis item' : 'item'}
              key={i}
            >
              {index !== this.data.week &&
              this.checkClock(this.formatDay(index - this.data.week, true)) ? (
                <i className="iconfont">&#xe645;</i>
              ) : (
                ''
              )}
              {this.weekZn[index]}
              <br /> {this.formatDay(index - this.data.week)}
            </div>
          ))}

          <div className="date" onClick={this.goDate.bind(this)}>
            <i className="iconfont icon-date">&#xe6a6;</i>
            <br />
            <i className="iconfont icon-arr">&#xe642;</i>
          </div>
        </ClockHead>
        <ClockToday>
          <Tag onClick={this.showPop.bind(this)}>打卡说明</Tag>
          <p>
            您已打卡{this.state.info && this.state.info.member_records.length}次
          </p>
          <video
            src={this.state.video}
            id="videoCont"
            preload="preload"
            onCanPlay={this.checkLength.bind(this)}
            style={{ display: 'none' }}
          />
          <input
            type="file"
            id="video"
            onChange={this.upload.bind(this)}
            accept="video/*"
            capture="camcorder"
          />
          {this.checkClock(this.formatDay(0, true)) ? (
            <button className="atthis">已打卡</button>
          ) : (
            <button onClick={this.camcorderPlay}>打卡</button>
          )}

          <p>打卡视频时长最多1分钟</p>
        </ClockToday>
        {!this.state.isToday ? (
          <ClockTitle>
            <span onClick={this.loadActiveList.bind(this)}>今日打卡</span>{' '}
            <b onClick={this.loadMemberList.bind(this)}>我的打卡记录</b>
          </ClockTitle>
        ) : (
          <ClockTitle>
            <span onClick={this.loadMemberList.bind(this)}>我的打卡记录</span>{' '}
            <b onClick={this.loadActiveList.bind(this)}>
              今日打卡{this.state.memberList && this.state.memberList.length}人
            </b>
          </ClockTitle>
        )}
        <ClockList>
          {this.state.memberList.map(item => {
            return (
              <ClockItem key={item.id}>
                <div className="head">
                  <div className="name">
                    <img
                      src={
                        (item.member && item.member.avatar) ||
                        this.props.userInfo.avatar
                      }
                      alt=""
                    />
                    {(item.member && item.member.nickname) ||
                      this.props.userInfo.nickname}
                  </div>
                  <div
                    className="ph"
                    onClick={this.goRank.bind(this, item.activity_id)}
                  >
                    <i className="iconfont">&#xe65b;</i>排行榜
                  </div>
                </div>
                <div className="tu">
                  {/* <i className="iconfont">&#xe601;</i> */}
                  {!this.state.isShow && (
                    <video
                      style={{ position: 'relative', zIndex: 10 }}
                      src={'http://www.yermn.com/' + item.content}
                      controls
                    />
                  )}
                </div>
                <div className="time">
                  <span
                    onClick={this.getPraise.bind(
                      this,
                      item.id,
                      item.activity_id
                    )}
                  >
                    <i className="iconfont">&#xe607;</i>点赞
                  </span>
                  {item.created_at}
                </div>
                <div className="des">
                  {item.points.map(item => {
                    return item.praise_name + '、'
                  })}
                  等人赞过。
                </div>
              </ClockItem>
            )
          })}
        </ClockList>
        <PopUp className={this.state.isShow ? 'show' : ''}>
          <div className="content">
            <h2>打卡说明</h2>
            <p>
              1、有明显眼部皱纹、眼袋、黑眼圈、眼角下垂者可进行打卡记录，作为“28天无效退款”依据；
              <br />
              2、未有明显眼部问题的顾客，无需打卡，作为高端眼部保养品使用即可；
              <br />
              打卡标准：每次使用1克（两粒黄豆大小），单边眼睛0.5克，手法提拉同时定点至太阳穴方向。
            </p>
            <b onClick={this.hidePop.bind(this)}>我知道了</b>
            <i className="iconfont" onClick={this.hidePop.bind(this)}>
              &#xe628;
            </i>
          </div>
        </PopUp>
      </div>
    )
  }
}

const mapStateToProps = state => ({
  userInfo: state.userInfo
})

export default connect(mapStateToProps)(Index)
